package com.tt.plat8.core;


import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: tangtao
 * Date: 14-2-19
 * Time: 下午5:30
 * To change this template use File | Settings | File Templates.
 */
public class TransactionSynchronizationManager {



    private static final ThreadLocal<Map<Object, Object>> resources =
            new ThreadLocal<Map<Object, Object>>();

    public static Map<Object, Object> getResourceMap() {
        Map<Object, Object> map = resources.get();
        return (map != null ? Collections.unmodifiableMap(map) : Collections.emptyMap());
    }

    public static boolean hasResource(Object key) {

        Object value = doGetResource(key);
        return (value != null);
    }


    public static void bindResource(Object key, Object value) throws IllegalStateException {

        Map<Object, Object> map = resources.get();
        // set ThreadLocal Map if none found
        if (map == null) {
            map = new HashMap<Object, Object>();
            resources.set(map);
        }
        map.put(key, value);

    }

    public static Object getResource(Object key) {
        Object value = doGetResource(key);
        return value;
    }

    private static Object doGetResource(Object key) {
        Map<Object, Object> map = resources.get();
        if (map == null) {
            return null;
        }
        Object value = map.get(key);
        return value;
    }
}
